import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import $baseUrl from '@/utils/baseURL'
const services = axios.create({
  baseURL: $baseUrl.iotUrl,
  timeout: 50000 // 请求超时时间
});

services.interceptors.request.use(
  config => {
    return config;
  },
  error => {
    console.log(error);
    return Promise.reject(error);
  }
);

// response interceptor
services.interceptors.response.use(
  response => {
    const res = response.data;
    if (![1, 200, '1', '200'].includes(res.code)) {
      if (res.msg) {
        Message({
          message: res.msg,
          type: 'warning',
          duration: 5 * 1000
        });
      }
    }
    return res;
  },
  error => {
    if (error.response) {
      const res = error.response.data;
      if (error.response.data.msg || error.response.data.message) {
        Message({
          message: error.response.data.msg || error.response.data.message,
          type: 'error',
          duration: 5 * 1000
        });
      } else {
        Message({
          message: '服务器异常',
          type: 'error',
          duration: 5 * 1000
        });
      }
      return Promise.reject(res);
    } else if (error.request) {
      Message({
        message: '服务器异常',
        type: 'error',
        duration: 5 * 1000
      });
    } else {
      Message({
        message: error.message,
        type: 'error',
        duration: 5 * 1000
      });
    }
    return Promise.reject(error);
  }
);

// 封装get请求
export function get(url, params = {}) {
  params.t = new Date().getTime(); // get方法加一个时间参数,解决ie下可能缓存问题.
  return services({
    url: url,
    method: 'get',
    params
  });
}

// 封装post请求
export function post(url, data = {}) {
  // 默认配置
  let sendObject = {
    url: url,
    method: 'post',
    data
  };
  sendObject.data = JSON.stringify(data);
  return services(sendObject);
}

export default services;

